const { success, failure } = require("../../utils/responses");
const commentsService = require("../../services/learn/commentsService");

/**
 * 获取评论列表
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.list = async (req, res) => {
  try {
    const { count, rows, pageSize, currentPage } =
      await commentsService.list(req);
    // 返回
    success(res, "评论查询成功", {
      lists: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 获取章节评论列表
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.getChapterById = async (req, res) => {
  try {
    const rows = await commentsService.all(req);
    success(res, "查询评论成功", formatComments(rows));
  } catch (error) {
    failure(res, error);
  }
};

// 封装方法来转换数据格式
function formatComments(rows) {
  if (rows.length === 0) return [];
  // 创建一个 map 用来存储每个评论的回复
  const repliesMap = new Map();

  // 遍历所有的行数据

  const parentList = rows.filter((row) => row.parentId === 0);
  parentList.forEach((row) => {
    // 初始化顶级评论的回复列表
    repliesMap.set(row.id, []);
  });
  const childList = rows.filter((row) => row.parentId !== 0);
  childList.forEach((row) => {
    // 如果有parentId，则查找对应的顶级评论并添加到回复列表中
    const parentComment = repliesMap.get(row.parentId);
    if (parentComment) {
      // 如果找到对应的顶级评论，则将当前评论添加到回复列表中
      repliesMap.set(row.parentId, [...parentComment, row]);
    }
  });

  // 最终的评论列表
  const formattedComments = [];

  // 再次遍历行数据，这次是为了构建最终的评论结构
  rows.forEach((row) => {
    if (row.parentId === 0) {
      // 如果没有parentId，则这是个顶级评论
      const comment = {
        ...row,
        reply: {
          total: repliesMap.get(row.id).length,
          list: repliesMap.get(row.id),
        },
      };
      formattedComments.push(comment);
    }
  });

  return formattedComments;
}

/**
 * 获取评论详情
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.details = async (req, res) => {
  try {
    const chapter = await commentsService.getById(req.query.id);
    success(res, "查询评论成功", chapter);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 添加评论
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.add = async (req, res) => {
  try {
    const body = filterBody(req);
    const chapter = await commentsService.create(body);
    success(res, "创建评论成功", chapter, 201);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 删除评论
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.del = async (req, res) => {
  try {
    await commentsService.delete(req.body.id);
    success(res, "删除评论成功");
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 更新评论
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.update = async (req, res) => {
  try {
    const body = filterBody(req);
    const chapter = await commentsService.update(req.body.id, body); //删除
    success(res, "更新评论成功", chapter);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 公共方法过滤白名单
 * @param req
 * @returns {{title, content: (string|string|DocumentFragment|*)}}
 */
function filterBody(req) {
  return {
    chapterId: req.body.chapterId,
    uid: req.body.uid,
    content: req.body.content,
    level: req.body.level,
    parentId: req.body.parentId,
    likes: req.body.likes,
    username: req.body.username,
    homeLink: req.body.homeLink,
    address: req.body.address,
    avatar: req.body.avatar,
    contentImg: req.body.contentImg,
  };
}
